package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"shop/api/request"
	"shop/initernal/dao"
	"shop/initernal/model"
)

func AddShop(c *gin.Context) {
	var req request.AddShop

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "获取参数失败",
			"data":    err.Error(),
		})
		return
	}
	var data model.Shop
	dao.GetOneByFields(&model.Shop{Title: req.Title}, &data)
	if data.Id > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "您的商品已经添加，请勿重复操作",
			"data":    nil,
		})
		return
	}
	shop := model.Shop{
		Title:     req.Title,
		Introduce: req.Introduce,
		Price:     req.Price,
	}
	if !dao.Create(&shop) {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "新增商品失败",
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "新增商品成功",
		"data":    shop,
	})
}

func QueryOneShop(c *gin.Context) {
	var req request.QueryOneShop

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "获取参数失败",
			"data":    err.Error(),
		})
		return
	}
	var shop model.Shop
	if !dao.GetOneById(req.Id, &shop) {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "该商品不存在",
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "商品详情展示成功",
		"data":    shop,
	})

}

func UpdateShop(c *gin.Context) {
	var req request.UpdateShop

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "获取参数失败",
			"data":    err.Error(),
		})
		return
	}
	var shop model.Shop
	dao.GetOneById(req.Id, &shop)
	if shop.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "该商品不存在",
			"data":    nil,
		})
		return
	}

	update := dao.Update(&model.Shop{
		Id:        shop.Id,
		Title:     req.Title,
		Introduce: req.Introduce,
		Price:     req.Price,
	})
	if !update {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "该商品修改失败",
			"data":    nil,
		})
		return
	}
	var data model.Shop

	dao.GetOneById(req.Id, &data)

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "商品修改成功",
		"data":    data,
	})
}

func DeleteShop(c *gin.Context) {
	var req request.DeleteShop

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "获取参数失败",
			"data":    err.Error(),
		})
		return
	}
	var shop model.Shop
	dao.GetOneById(req.Id, &shop)
	if shop.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "该商品不存在",
			"data":    nil,
		})
		return
	}

	if !dao.Delete(&shop) {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "该商品删除失败",
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "商品删除成功",
		"data":    nil,
	})

}
